// packagesA/pages/tally/index.js
const app = getApp()
const myRequest = require('../../../utils/request'); // 导入整个模块
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '../../../store/tally/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0,
    iconindex: 0,
    iconsrc: '',
    active: 0,
    addshow: false,
    bottomInset: 0,
    year: '',
    month: '',
    inputnum: 0.00,
    outputnum: 0.00,
    nowdate: new Date().getTime(),
    date: new Date().getTime(),
    maxDate: new Date().getTime(),
    minDate: new Date(1900, 1, 1).getTime(),
    dateshow: false,
    calcshow: false,
    caldate: '',
    calshow: false,
    groupItemsByDate: [],
    remark: '', //备注
    outicon: [{
        image: "./images/icon/a-068_yongcan.png",
        text: "餐饮",
        index: 1
      },
      {
        image: "./images/icon/a-068_gouwu.png",
        text: "购物",
        index: 2
      },
      {
        image: "./images/icon/a-068_shenghuo.png",
        text: "日用",
        index: 3
      },
      {
        image: "./images/icon/a-068_gongjiao.png",
        text: "交通",
        index: 4
      },
      {
        image: "./images/icon/a-068_maicai.png",
        text: "蔬菜",
        index: 5
      },
      {
        image: "./images/icon/a-068_yinpin.png",
        text: "饮品",
        index: 6
      },
      {
        image: "./images/icon/a-068_shuiguo.png",
        text: "水果",
        index: 7
      },
      {
        image: "./images/icon/a-068_yundong.png",
        text: "运动",
        index: 8
      },
      {
        image: "./images/icon/a-068_huazhuang.png",
        text: "美容",
        index: 9
      },
      {
        image: "./images/icon/a-068_huafei.png",
        text: "学费",
        index: 10
      },
      {
        image: "./images/icon/a-068_jiuyi.png",
        text: "就医",
        index: 11
      },
      {
        image: "./images/icon/a-068_chongwu.png",
        text: "宠物",
        index: 12
      },
      {
        image: "./images/icon/a-068_dianying.png",
        text: "电影",
        index: 13
      },
      {
        image: "./images/icon/a-068_lvyou.png",
        text: "旅行",
        index: 14
      },
      {
        image: "./images/icon/a-068_wenju.png",
        text: "学习",
        index: 15
      },
      {
        image: "./images/icon/a-068_zhuangxiu.png",
        text: "装修",
        index: 16
      },
      {
        image: "./images/icon/a-068_lingshi.png",
        text: "零食",
        index: 17
      },
      {
        image: "./images/icon/a-068_fangdai.png",
        text: "房贷",
        index: 18
      },
      {
        image: "./images/icon/a-068_shuma.png",
        text: "数码",
        index: 19
      },
      {
        image: "./images/icon/a-068_meifa.png",
        text: "美发",
        index: 20
      },
      {
        image: "./images/icon/a-068_liwu.png",
        text: "礼物",
        index: 21
      },
      {
        image: "./images/icon/a-068_muying.png",
        text: "母婴",
        index: 22
      },
      {
        image: "./images/icon/a-068_lijin.png",
        text: "亲友",
        index: 23
      },
      {
        image: "./images/icon/a-068_xinyongka.png",
        text: "信用卡",
        index: 24
      },
      {
        image: "./images/icon/a-068_youxi.png",
        text: "游戏",
        index: 25
      },
      {
        image: "./images/icon/a-068_xianhua.png",
        text: "鲜花",
        index: 26
      },
      {
        image: "./images/icon/a-068_yanchanghui.png",
        text: "演唱会",
        index: 27
      },
      {
        image: "./images/icon/a-068_jiaocai.png",
        text: "话费",
        index: 28
      },
      {
        image: "./images/icon/a-068_jiaju.png",
        text: "家具",
        index: 29
      },
      {
        image: "./images/icon/a-068_shezhi.png",
        text: "设置",
        index: 30
      }
    ],
    inicon: [{
        image: "./images/icon/a-068_gongzi.png",
        text: "工资",
        index: 1
      },
      {
        image: "./images/icon/a-068_jianzhi.png",
        text: "兼职",
        index: 2
      },
      {
        image: "./images/icon/a-068_lijin.png",
        text: "礼金",
        index: 3
      },
      {
        image: "./images/icon/a-068_licai.png",
        text: "理财",
        index: 4
      },
      {
        image: "./images/icon/a-068_qita-60.png",
        text: "其他",
        index: 5
      },
      {
        image: "./images/icon/a-068_shezhi.png",
        text: "设置",
        index: 6
      }
    ],
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    scrollTop: 0,
    target: 'num1', //表示当前正在输入哪个数字，取num1或num2
    num1: '',
    num2: '',
    op: '',
    num: '0',
    username: '',
    payinfo: [],
    filterpayinfo: [], //筛选后要显示的数组
  },
  // 滚动事件监听
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop,
    })
  },
  //输入数字
  numBtn(e) {

    const val = e.currentTarget.dataset.val
    //输入小数点时，小数点左边要有数
    if (this.data.op && !this.data.num2 && val == '.') return
    //连续输入.
    if (this.data.num.charAt(this.data.num.length - 1) == '.' && val == '.') return
    //一个操作数是0.几
    if (!this.data.num1 && val == '.') {
      return this.setData({
        num1: '0.',
        num: '0.'
      })
    }

    //第一操作数都没有就输入0
    if (!this.data.num1 && val == '0') return
    // 输入第一操作数
    if (!this.data.num1 || !this.data.op) return this.setData({
      num1: this.data.num1 + val,
      num: !this.data.num1 ? val : this.data.num + val
    })
    // 给第二位数添加位数
    if (this.data.op) return this.setData({
      num2: this.data.num2 + val,
      num: this.data.num + val
    })



  },
  // 运算符按钮事件
  opBtn: function (e) {
    if (!this.data.num2 && this.data.op) return
    if (this.data.num1 && this.data.num2 && this.data.op) {
      this.calculate()
    }

    this.setData({
      op: e.target.dataset.val
    });
    this.setData({
      num: this.data.num + this.data.op
    })
  },

  //撤回
  backspace() {
    if (!this.data.num1) return
    //撤回的是第一操作数
    if (!this.data.op) return this.setData({
      num1: this.data.num1.slice(0, -1),
      num: !this.data.num.slice(0, -1) ? '0' : this.data.num.slice(0, -1)
    })
    //撤回的是运算符
    if (this.data.op && !this.data.num2) return this.setData({
      op: '',
      num: this.data.num.slice(0, -1)
    })
    //撤回的是第二操作数
    if (this.data.num2) return this.setData({
      num2: this.data.num2.slice(0, -1),
      num: this.data.num.slice(0, -1)
    })
    this.setData({
      num: !this.data.num.slice(0, -1) ? '0' : this.data.num.slice(0, -1)
    })


  },
  //等于
  calculate() {
    if (!this.data.num1 || !this.data.num2 || !this.data.op) return
    const first = parseFloat(this.data.num1);
    const second = parseFloat(this.data.num2);
    let result = 0;
    if (this.data.op == '+') {
      result = first + second;
    } else {
      result = first - second;
    }
    result = result.toString(); // 将计算结果转换为字符串类型显示
    this.setData({
      op: '',
      num1: result,
      num2: '',
      num: result
    })

  },
  reset() {
    this.setData({
      num1: '',
      num2: '',
      op: '',
      num: '0',
      caldate: this.getcaldate(new Date().getTime()),
      iconindex: 0,
      active: 0,

      remark: ''
    })
  },

  //点击详情
  godetail(e) {
    console.log(e);
    this.updatepayinfo(this.data.payinfo)
    wx.navigateTo({
      url: '/packagesA/pages/tally/tallydetail/index?item=' + JSON.stringify(e.currentTarget.dataset.item),
    })
  },
  finish() {
    let that = this
    let data = {
      remark: this.data.remark,
      date: this.data.caldate,
      num: this.data.num,
      active: this.data.active,
      category: !this.data.active ? '支出' : '收入',
      iconsrc: !this.data.active ? this.data.outicon[this.data.iconindex - 1].image : this.data.inicon[this.data.iconindex - 1].image,
      iconname: !this.data.active ? this.data.outicon[this.data.iconindex - 1].text : this.data.inicon[this.data.iconindex - 1].text,
    }
    myRequest.post('/pay/add', {
      username: this.data.username,
      data: data
    }).then(res => {
      wx.showToast({
        title: '谢增成功！',
        icon: 'success',
        duration: 2000
      })

      that.getpayinfo()
      that.setData({
        addshow: false,
        calcshow: false
      })
    })
    
    this.reset()
  },
  // 分组并计算每天的支出和收入
  groupItemsByDate: function (items) {
    const dailySummary = items.reduce((result, item) => {
      // 根据日期分组
      const dateKey = item.date;
      if (!result[dateKey]) {
        result[dateKey] = {
          date: item.date,
          items: [],
          income: 0,
          expense: 0
        };
      }

      // 累加收入和支出
      if (item.active === 0) {
        result[dateKey].expense += Number(item.num);
      } else if (item.active === 1) {
        result[dateKey].income += Number(item.num);
      }

      // 将当前项添加到对应日期的items数组中
      result[dateKey].items.push(item);

      return result;
    }, {});

    // 将对象的值转换为数组，并按照日期从近到远排序
    return Object.values(dailySummary).sort((a, b) => {
      return new Date(b.date) - new Date(a.date); // 降序排序
    });
  },
  //数据整理
  settledata() {

    let tempdata = this.data.payinfo.filter((val) => {
      return val.date.split('/')[0] == this.data.year && val.date.split('/')[1] == this.data.month
    })
    let inputnum = 0
    let outputnum = 0

    tempdata.forEach((val) => {
      if (!val.active) {
        outputnum += Number(val.num)
      } else {
        inputnum += Number(val.num)
      }
    })


    this.setData({
      filterpayinfo: tempdata,
      inputnum: inputnum.toFixed(2),
      outputnum: outputnum.toFixed(2),
      groupItemsByDate: this.groupItemsByDate(tempdata)
    })
  },
  //获取记录
  getpayinfo() {
    let that = this
    myRequest.get('/pay/paydata',{username:this.data.username}).then(res=>{
      that.setData({
        payinfo: res.data
      })
      that.settledata()
    })
 
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['payinfo'],
      actions: ['updatepayinfo']
    })
    const systemInfo = wx.getWindowInfo();
    const bottomInset = Math.abs(systemInfo.safeArea.bottom - systemInfo.windowHeight);
    const date = new Date()
    this.setData({
      year: date.getFullYear(),
      month: (date.getMonth() + 1).toString().padStart(2, '0'),
      bottomInset: bottomInset + 20,
      active: 0,
      caldate: this.getcaldate(new Date().getTime()),
      username: JSON.parse(wx.getStorageSync('userinfo')).username
    })
    this.getpayinfo()
  },

  // 备注输入
  remarkinput(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  //点击图标
  selecticon(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      iconindex: index,
      calcshow: true,
      iconsrc: !this.data.active ? this.data.outicon[index - 1].image : this.data.inicon[index - 1].image
    })

  },
  onChange(event) {
    this.setData({
      active: event.detail.name
    })

  },
  add() {
    this.setData({
      addshow: true
    })
  },
  // 时间弹窗显示
  updatetime() {
    this.setData({
      dateshow: true
    })
  },
  closedate() {
    this.setData({
      dateshow: false
    })
  },

  showcalcdate() {
    this.setData({
      calshow: true
    })
  },
  oncalClose() {
    this.setData({
      calshow: false
    })
  },
  closecalc() {
    this.reset()
    this.setData({
      calcshow: false
    })
  },
  getcaldate(givenTimestamp) {
    // 创建一个Date对象
    const date = new Date(givenTimestamp); // 将秒转换为毫秒

    // 格式化日期
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');

    // 组合成YYYY/MM/DD格式的字符串
    return `${year}/${month}/${day}`;

  },
  changecaldate(e) {
    // 创建一个Date对象
    const date = new Date(e.detail); // 将秒转换为毫秒
    this.setData({
      caldate: this.getcaldate(date),
      calshow: false
    })
  },
  changedate(e) {
    // 创建一个Date对象
    const date = new Date(e.detail); // 将秒转换为毫秒
    this.setData({
      year: date.getFullYear(),
      month: (date.getMonth() + 1).toString().padStart(2, '0'),
      dateshow: false
    })
    this.settledata()

  },

  //取消记录  
  cancel() {
    console.log(111);
    this.setData({
      addshow: false
    })
  },
  closeadd() {
    this.reset()
    this.setData({
      addshow: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getpayinfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})